<template>
  <div class="user-avator-dropdown">
    <Dropdown @on-click="handleDropdownClick">
      <span style="font-size: 20px; font-family: 新宋体">{{ username }}</span>
      <Icon :size="18" type="md-arrow-dropdown"></Icon>
      <DropdownMenu slot="list">
        <DropdownItem name="user">个人信息</DropdownItem>
        <DropdownItem name="changePwd">修改密码</DropdownItem>
        <DropdownItem name="logout">退出登录</DropdownItem>
      </DropdownMenu>
    </Dropdown>

    <Modal v-model="userModal" title="个人信息" :mask-closable="false">
      <Form
        label-position="right"
        :label-width="120"
        ref="userForm"
        :model="userForm"
        :rules="userValidate"
      >
        <FormItem label="用户名" prop="username">
          <Input readonly v-model="userForm.username" />
        </FormItem>
        <FormItem label="真实姓名" prop="real_name">
          <Input
            clearable
            placeholder="请输入真实姓名"
            v-model="userForm.real_name"
          />
        </FormItem>
        <FormItem label="性别" prop="gender">
          <RadioGroup v-model="userForm.gender">
            <Radio label="male">男</Radio>
            <Radio label="female" style="margin-left: 20px">女</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="联系电话" prop="phone">
          <Input
            clearable
            placeholder="请输入联系电话"
            v-model="userForm.phone"
          />
        </FormItem>
        <FormItem label="电子邮箱" prop="email">
          <Input
            clearable
            placeholder="请输入电子邮箱"
            v-model="userForm.email"
          />
        </FormItem>
        <FormItem label="创建时间" prop="create_time">
          <DatePicker
            readonly
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            v-model="userForm.create_time"
            style="width: 100%"
          ></DatePicker>
        </FormItem>
        <FormItem label="最近修改时间" prop="update_time">
          <DatePicker
            readonly
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            v-model="userForm.update_time"
            style="width: 100%"
          ></DatePicker>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input v-model="userForm.remark" type="textarea" :rows="3" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="handleUserCancel">取消</Button>
        <Button type="primary" @click="handleUserSubmit('userForm')"
          >修改</Button
        >
      </div>
    </Modal>

    <Modal v-model="changePwdModal" title="修改密码" :mask-closable="false">
      <Form
        label-position="right"
        :label-width="120"
        ref="changePwdForm"
        :model="changePwdForm"
        :rules="changePwdValidate"
      >
        <FormItem label="旧密码" prop="old_password">
          <Input
            clearable
            placeholder="请输入旧密码"
            v-model="changePwdForm.old_password"
            type="password"
          />
        </FormItem>
        <FormItem label="新密码" prop="password">
          <Input
            clearable
            placeholder="请输入新密码"
            v-model="changePwdForm.password"
            type="password"
          />
        </FormItem>
        <FormItem label="确认密码" prop="confirm_password">
          <Input
            clearable
            placeholder="请输入确认密码"
            v-model="changePwdForm.confirm_password"
            type="password"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="handleChangePwdCancel">取消</Button>
        <Button type="primary" @click="handleChangePwdSubmit('changePwdForm')"
          >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import "./user.less";
import { mapActions } from "vuex";
import { changePwd, updateUser } from "@/api/HttpAutoTestService/user";

export default {
  name: "User",
  data() {
    const validateNewPwd = (rule, value, callback) => {
      if (
        this.changePwdForm.password !== "" &&
        this.changePwdForm.confirm_password !== ""
      ) {
        if (
          value !== this.changePwdForm.password ||
          value !== this.changePwdForm.confirm_password
        ) {
          callback(new Error("新密码不一致，请重新输入！"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号"));
      }
      callback();
    };
    return {
      username: this.$store.state.user.username,
      userModal: false,
      changePwdModal: false,
      userForm: {
        id: "",
        username: "",
        real_name: "",
        gender: "",
        phone: "",
        email: "",
        create_time: "",
        update_time: "",
        remark: "",
      },
      changePwdForm: {
        old_password: "",
        password: "",
        confirm_password: "",
      },
      userValidate: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        real_name: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" },
        ],
        gender: [
          { required: true, message: "性别不能为空", trigger: "change" },
        ],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          {
            type: "string",
            min: 11,
            max: 11,
            message: "请输入11位手机号",
            trigger: "blur",
          },
          { validator: validatePhone, trigger: "blur" },
        ],
        email: [
          { required: true, message: "电子邮箱不能为空", trigger: "blur" },
          { type: "email", message: "电子邮箱格式不正确", trigger: "blur" },
        ],
      },
      changePwdValidate: {
        old_password: [
          { required: true, message: "旧密码不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { validator: validateNewPwd, trigger: "blur" },
        ],
        confirm_password: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { validator: validateNewPwd, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    ...mapActions(["getUser", "handleLogOut"]),

    logout() {
      this.handleLogOut().then(() => {
        this.$router.push({
          name: "login",
        });
      });
    },

    handleDropdownClick(name) {
      switch (name) {
        case "user":
          this.getUser().then((res) => {
            this.userForm = res;
            this.userModal = true;
          });
          break;
        case "changePwd":
          this.changePwdModal = true;
          break;
        case "logout":
          this.logout();
          break;
      }
    },

    handleUserCancel() {
      this.userModal = false;
      this.userForm = {};
    },

    handleUserSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let { id, real_name, gender, phone, email, remark } = this.userForm;
          updateUser({ id, real_name, gender, phone, email, remark })
            .then((res) => {
              if (res.status === 200) {
                this.$Message.info("修改成功");
                this.handleUserCancel();
              } else {
                this.$Message.error("修改失败");
              }
            })
            .catch((err) => {
              this.$Modal.error({
                title: "系统异常，请联系管理员……",
                content: JSON.stringify(err),
                closable: true,
              });
            });
        }
      });
    },

    handleChangePwdSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let data = {
            id: this.$store.state.user.id,
            old_password: this.changePwdForm.old_password,
            password: this.changePwdForm.password,
          };
          changePwd(data)
            .then((res) => {
              if (res.status === 200) {
                this.$Message.info("修改成功，请重新登录！");
                this.handleChangePwdCancel();
                this.logout();
              } else {
                this.$Message.error("修改失败");
              }
            })
            .catch((err) => {
              this.$Modal.error({
                title: "系统异常，请联系管理员……",
                content: JSON.stringify(err),
                closable: true,
              });
            });
        }
      });
    },

    handleChangePwdCancel() {
      this.changePwdModal = false;
      this.changePwdForm = {};
    },
  },
};
</script>
